﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using Telerik.Web.UI;
using SalePartial.BLL;
using System.Data;
using SalePartial.Utility;

public partial class Roles_UsersAndRoles : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            //修改页头
            //Page.Header.Title = String.Format("环球零件资源网--用户管理");
            LoginUserType type = RoleControlManager.checkUserAuthority(User.Identity.Name);
            if (type != LoginUserType.ADMIN)
            {
                Response.Redirect(GlobalSetting.UrlHomePage, true);
            }
            //// 绑定的用户和角色
            //BindUsersToUserList();
            //BindRolesToList();
            ////显示这些用户属于当前选定的角色
            //DisplayUsersBelongingToRole();
            //BindFilteringUI();
        } 
    }


    protected void Btn_Set_Click(object sender, EventArgs e)
    {
        sqlDSRoleUser.SelectParameters["isLocked"].DefaultValue = cbIsLockOut.Checked.ToString();
        sqlDSRoleUser.SelectParameters["UserName"].DefaultValue =
            tbUserName.Text.Trim() == string.Empty ? "%" : tbUserName.Text.Trim();
        sqlDSRoleUser.SelectParameters["createStDay"].DefaultValue =
            dpCreateStDay.SelectedDate == null ? "19000101" : string.Format("{0:yyyyMMdd}", dpCreateStDay.SelectedDate);
        sqlDSRoleUser.SelectParameters["createEdDay"].DefaultValue =
            dpCreateEdDay.SelectedDate == null ? "20991231" : string.Format("{0:yyyyMMdd}", dpCreateEdDay.SelectedDate);
        sqlDSRoleUser.SelectParameters["lastLoginStDay"].DefaultValue =
            dpLastLoginStDay.SelectedDate == null ? "19000101" : string.Format("{0:yyyyMMdd}", dpLastLoginStDay.SelectedDate);
        sqlDSRoleUser.SelectParameters["lastLoginEdDay"].DefaultValue =
            dpLastLoginEdDay.SelectedDate == null ? "20991231" : string.Format("{0:yyyyMMdd}", dpLastLoginEdDay.SelectedDate);


        rgridRoleUser.DataBind();
    }

    protected void rgridRoleUser_UpdateCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
    {
        //string UserId = ((GridDataItem)e.Item).OwnerTableView.DataKeyValues[e.Item.ItemIndex]["UserId"].ToString();
        //string RoleId = ((GridDataItem)e.Item).OwnerTableView.DataKeyValues[e.Item.ItemIndex]["RoleId"].ToString();

        GridEditableItem editedItem = (GridEditableItem)e.Item;
        GridEditManager editMan = editedItem.EditManager;

        string UserId = editedItem.GetDataKeyValue("UserId").ToString();
        string RoleId = editedItem.GetDataKeyValue("RoleId").ToString();

        RadComboBox rcmbRoleId = (RadComboBox)editMan.GetColumnEditor("RoleId").ContainerControl.Controls[0];
        RadDatePicker rdpModerateDate = (RadDatePicker)editMan.GetColumnEditor("ModerateDate").ContainerControl.FindControl("RDPModerateDate");

        if (rcmbRoleId.SelectedValue.ToString() != RoleId)
        {
            DataTable dt = UserBLL.SelectUserInRole(rcmbRoleId.SelectedValue.ToString(), UserId);

            if (dt != null && dt.Rows.Count > 0 && dt.Rows[0][0].ToString() != "0")
            {
                rgridRoleUser.Controls.Add(new LiteralControl("此‘角色名称’已经使用，请重新设置!"));
                return;
            }
        }

        UserBLL.UpdateUserInRole(RoleId, UserId, rcmbRoleId.SelectedValue.ToString(), rcmbRoleId.Text,Convert.ToDateTime(rdpModerateDate.DbSelectedDate));
    }


    protected void rgridRoleUser_InsertCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
    {

    }

    protected void rgridRoleUser_DeleteCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
    {
        string UserId = ((GridDataItem)e.Item).OwnerTableView.DataKeyValues[e.Item.ItemIndex]["UserId"].ToString();
        string RoleId = ((GridDataItem)e.Item).OwnerTableView.DataKeyValues[e.Item.ItemIndex]["RoleId"].ToString();

        UserBLL.DeleteUserInRole(RoleId, UserId);
        
        rgridRoleUser.DataBind();
    }

    protected void rgridRoleUser_ItemCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
    {
        switch (e.CommandName)
        {
            case "approve":
                Guid userid = (Guid)e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["UserId"];
                GridDataItem dataItem = (GridDataItem)e.Item;
                CheckBox checkbx = (CheckBox)dataItem["IsLockedOut"].FindControl("cbIsLockedOut");
                bool isLockedOut = checkbx.Checked;
                checkbx = (CheckBox)dataItem["IsApproved"].FindControl("cbIsApproved");
                bool isApproved = checkbx.Checked;
                bool rt = UserBLL.UpdateUser(userid, isLockedOut, isApproved);
                if (rt)
                {
                    //success
                    e.Item.OwnerTableView.Rebind();

                }
                else
                {
                }
                break;
        }

    }


    protected void rgridRoleUser_ItemCreated(object sender, Telerik.Web.UI.GridItemEventArgs e)
    {
        if (e.Item is GridHeaderItem)
        {
            GridHeaderItem header = (GridHeaderItem)e.Item;
            //header["CompanyName"].Text = "TEST";
        }
        else if (e.Item is GridDataItem)
        {
            //GridDataItem dataItem = (GridDataItem)e.Item;

            //DataRowView DataRV = (DataRowView)e.Item.DataItem;

            //GridEditableItem editedItem = (GridEditableItem)e.Item;
            //GridEditManager editMan = editedItem.EditManager;

            //RadDatePicker rdp = (RadDatePicker)editMan.GetColumnEditor("ModerateDate").ContainerControl.FindControl("RDPModerateDate");

            //Label lblDate = (Label)dataItem["ModerateDate"].FindControl("LblModerateDate");

            //if (DataRV != null && DataRV.Row["ModerateDate"] != null
            //    && DataRV.Row["ModerateDate"].ToString() != string.Empty)
            //{
            //    DateTime ModerateDate = Convert.ToDateTime(DataRV.Row["ModerateDate"].ToString());
            //    if (DateTime.Compare(ModerateDate, rdp.MinDate) < 0)
            //    {
            //        rdp.SelectedDate = rdp.MinDate;
            //        lblDate.Text = rdp.MinDate.ToString("yyyy/MM/dd");
            //    }
            //    else if (DateTime.Compare(ModerateDate, rdp.MaxDate) > 0)
            //    {
            //        rdp.SelectedDate = rdp.MaxDate;
            //        lblDate.Text = rdp.MaxDate.ToString("yyyy/MM/dd");
            //    }
            //    else
            //    {
            //        rdp.SelectedDate = ModerateDate;
            //        lblDate.Text = ModerateDate.ToString("yyyy/MM/dd");
            //    }
            //}
            //else
            //{
            //    rdp.Enabled = false;
            //}

        }
    }




    //protected void UserList_SelectedIndexChanged(object sender, EventArgs e)
    //{
    //    CheckRolesForSelectedUser();
    //}

    //protected void RoleList_SelectedIndexChanged(object sender, EventArgs e)
    //{
    //    DisplayUsersBelongingToRole();
    //}

    //protected void RoleCheckBox_CheckChanged(object sender, EventArgs e)
    //{
    //    // 提出复选框事件
    //    CheckBox RoleCheckBox = sender as CheckBox;

    //    // 获取当前选定的用户和角色 
    //    string selectedUserName = UserList.SelectedValue.ToString();
    //    string roleName = RoleCheckBox.Text;
    //    if (UserList.SelectedValue.ToString() == null)
    //    {
    //        RoleCheckBox.Enabled = false;
    //    }
    //    // 确定从某个角色需要添加或删除用户
    //    if (RoleCheckBox.Checked)
    //    {
    //        // 将用户添加到角色
    //        Roles.AddUserToRole(selectedUserName, roleName);
    //        // 显示一条状态消息
    //        ActionStatus.Text = string.Format("用户 {0} 被添加到角色 {1}.", selectedUserName, roleName);
    //    }
    //    else
    //    {
    //        // 从角色中删除用户 
    //        Roles.RemoveUserFromRole(selectedUserName, roleName);
    //        // 显示一条状态消息
    //        ActionStatus.Text = string.Format("用户 {0} 从角色 {1} 中删除 .", selectedUserName, roleName);
    //    }

    //    // 刷新界面 
    //    DisplayUsersBelongingToRole();
    //}
    //protected void RolesUserList_RowDeleting(object sender, GridViewDeleteEventArgs e)
    //{
    //    // 获取选定的角色
    //    string selectedRoleName = RoleList.SelectedValue;

    //    //查询用户名Label
    //    Label UserNameLabel = RolesUserList.Rows[e.RowIndex].FindControl("UserNameLabel") as Label;

    //    // 从角色中删除用户
    //    Roles.RemoveUserFromRole(UserNameLabel.Text, selectedRoleName);

    //    // 在GridView刷新
    //    DisplayUsersBelongingToRole();

    //    // 显示一条状态消息
    //    ActionStatus.Text = string.Format("用户 {0} 从角色 {1} 中删除 .", UserNameLabel.Text, selectedRoleName);

    //    // 刷新用户界面
    //    CheckRolesForSelectedUser();
    //}
    //protected void AddUserToRoleButton_Click(object sender, EventArgs e)
    //{
    //    // 获取选定的角色和用户名
    //    string selectedRoleName = RoleList.SelectedValue;
    //    string userNameToAddToRole = UserNameToAddToRole.Text;

    //    // 确保输入的一个值
    //    if (userNameToAddToRole.Trim().Length == 0)
    //    {
    //        ActionStatus.Text = "你必须在文本框中输入一个用户名.";
    //        return;
    //    }

    //    // 确保用户在系统中存在
    //    MembershipUser userInfo = Membership.GetUser(userNameToAddToRole);
    //    if (userInfo == null)
    //    {
    //        ActionStatus.Text = string.Format("此用户 {0} 不存在.", userNameToAddToRole);
    //        return;
    //    }

    //    // 确保该用户已经不属于这个角色 
    //    if (Roles.IsUserInRole(userNameToAddToRole, selectedRoleName))
    //    {
    //        ActionStatus.Text = string.Format("用户 {0} 已是角色 {1} 的成员 .", userNameToAddToRole, selectedRoleName);
    //        return;
    //    }

    //    // If we reach here, we need to add the user to the role 
    //    Roles.AddUserToRole(userNameToAddToRole, selectedRoleName);

    //    // 清除文本框
    //    UserNameToAddToRole.Text = string.Empty;

    //    // 刷新此GridView 
    //    DisplayUsersBelongingToRole();

    //    // Display a status message 
    //    ActionStatus.Text = string.Format("用户 {0} 被添加到角色 {1}.", userNameToAddToRole, selectedRoleName);

    //    // Refresh the "by user" interface 
    //    CheckRolesForSelectedUser();
    //}

    //private void BindUsersToUserList()
    //{
    //    int totalRecords;
    //    UserList.DataSource = Membership.FindUsersByName(this.UsernameToMatch + "%", this.PageIndex,
    //                        this.PageSize, out totalRecords);
    //    UserList.DataBind();

    //    // 启用/禁用分页界面
    //    bool visitingFirstPage = (this.PageIndex == 0);
    //    lnkFirst.Enabled = !visitingFirstPage;
    //    lnkPrev.Enabled = !visitingFirstPage;

    //    int lastPageIndex = (totalRecords - 1) / this.PageSize;
    //    bool visitingLastPage = (this.PageIndex >= lastPageIndex);
    //    lnkNext.Enabled = !visitingLastPage;
    //    lnkLast.Enabled = !visitingLastPage;
    //}

    //private void BindRolesToList()
    //{
    //    // 获取的所有角色
    //    string[] roles = Roles.GetAllRoles();
    //    UsersRoleList.DataSource = roles;
    //    UsersRoleList.DataBind();

    //    RoleList.DataSource = roles;
    //    RoleList.DataBind();
    //}

    //private void CheckRolesForSelectedUser()
    //{
    //    // 确定选定的用户属于什么角色 
    //    string selectedUserName = UserList.SelectedValue.ToString();
    //    string[] selectedUsersRoles = Roles.GetRolesForUser(selectedUserName);

    //    //遍历Repeater的项目，根据需要检查或取消选中该复选框 
    //    foreach (RepeaterItem ri in UsersRoleList.Items)
    //    {
    //        //参考复选框 编程
    //        CheckBox RoleCheckBox = ri.FindControl("RoleCheckBox") as CheckBox;
    //        // See if RoleCheckBox.Text is in selectedUsersRoles 
    //        if (selectedUsersRoles.Contains<string>(RoleCheckBox.Text))
    //            RoleCheckBox.Checked = true;
    //        else
    //            RoleCheckBox.Checked = false;
    //    }
    //}

    //private void DisplayUsersBelongingToRole()
    //{
    //    // 获取选定的角色
    //    string selectedRoleName = RoleList.SelectedValue;

    //    // 从角色列表中获取用户名
    //    string[] usersBelongingToRole = Roles.GetUsersInRole(selectedRoleName);

    //    // 绑定用户的列表到GridView
    //    RolesUserList.DataSource = usersBelongingToRole;
    //    RolesUserList.DataBind();
    //}

    ////按首字母排序
    //private void BindFilteringUI()
    //{
    //    string[] filterOptions = { "All", "A", "B", "C","D", "E", "F", "G", "H", "I","J", "K", "L", "M", "N", "O","P",
    // "Q", "R", "S", "T", "U","V", "W", "X", "Y", "Z" };
    //    FilteringUI.DataSource = filterOptions;
    //    FilteringUI.DataBind();
    //}
    //private string UsernameToMatch
    //{
    //    get
    //    {
    //        object o = ViewState["UsernameToMatch"];
    //        if (o == null)
    //            return string.Empty;
    //        else
    //            return (string)o;
    //    }
    //    set
    //    {
    //        ViewState["UsernameToMatch"] = value;
    //    }
    //}
    //protected void FilteringUI_ItemCommand(object source, RepeaterCommandEventArgs e)
    //{
    //    if (e.CommandName == "All")
    //    {
    //        this.UsernameToMatch = string.Empty;
    //    }
    //    else
    //    {
    //        this.UsernameToMatch = e.CommandName;
    //    }
    //    BindUsersToUserList();
    //}

    ////分页
    //private int PageIndex
    //{
    //    get
    //    {
    //        object o = ViewState["PageIndex"];
    //        if (o == null)
    //            return 0;
    //        else
    //            return (int)o;
    //    }
    //    set
    //    {
    //        ViewState["PageIndex"] = value;
    //    }
    //}

    //private int PageSize
    //{
    //    get
    //    {
    //        return 15;
    //    }
    //}
    //protected void lnkFirst_Click(object sender, EventArgs e)
    //{
    //    this.PageIndex = 0;
    //    BindUsersToUserList();
    //}

    //protected void lnkPrev_Click(object sender, EventArgs e)
    //{
    //    this.PageIndex -= 1;
    //    BindUsersToUserList();
    //}

    //protected void lnkNext_Click(object sender, EventArgs e)
    //{
    //    this.PageIndex += 1;
    //    BindUsersToUserList();
    //}

    //protected void lnkLast_Click(object sender, EventArgs e)
    //{
    //    // 确定的记录总数
    //    int totalRecords;
    //    Membership.FindUsersByName(this.UsernameToMatch + "%", this.PageIndex, this.PageSize, out totalRecords);
    //    // 导航到最后一页指数
    //    this.PageIndex = (totalRecords - 1) / this.PageSize;
    //    BindUsersToUserList();
    //}
}
